<script lang="ts">
    import { url, Baud_rate, Serial_select_value, link_working, temp_str, cancelmotioning, send_rate } from '$lib/data';
    import { listen_serial, close_serialport, recv_serial_event, send_serial_emit } from '$lib/link';
    url.set("/settings");

    import { onMount } from 'svelte';
    import { Alert, Label, Button, Toast, InputAddon, NumberInput, ButtonGroup } from 'flowbite-svelte';
    import { InfoCircleSolid, ExclamationCircleSolid, CheckCircleSolid } from 'flowbite-svelte-icons';

    import { quintOut, elasticOut, backOut } from 'svelte/easing';
    import { fade, fly, draw, slide } from 'svelte/transition';

    import Serial from './SerialSetting.svelte'
    import SerialSetting from './SerialSetting.svelte';

    //串行设置的元素
    let SerialArray:Array<string> = [
        "Serial_select",
        "Baud_rate"
    ];

    // //防止link()被多次调用
    // let link_working:boolean = false; 

    let link_OK_Toast:boolean = false;
    let link_OKed_Toast:boolean = false;
    let link_error_Toast:boolean = false;
    let link_error_Toast_text:string = "";

    let link_close_Toast:boolean = false;
    let link_close_Toast_text:string = "";

    async function link() {
        //判断与设定工作中防止多次调用
        if ($link_working) {
            link_OKed_Toast = true;
            setTimeout(() => {link_OKed_Toast = false}, 3000);
            return;
        }
        $link_working = true;

        //如果未选择
        if($Serial_select_value == ""){
            link_error_Toast = true;
            $link_working = false

            link_error_Toast_text = "请选择端口";
            setTimeout(() => {link_error_Toast = false}, 3000);
            return;
        }
        
        // await send_serial_emit("colse");
        let msg = await listen_serial($Serial_select_value, $Baud_rate);
        console.log(msg);
        if(msg == "OK"){
            recv_serial_event();
            link_OK_Toast = true;
            setTimeout(() => {link_OK_Toast = false}, 3000);
        }else{
            link_error_Toast = true;
            $link_working = false;

            link_error_Toast_text = "该端口可能已被其他设备链接";
        }

        setTimeout(() => {link_error_Toast = false}, 3000);
    }
    async function close_link() {
        let msg = await send_serial_emit("colse");//提示下位机

        if($link_working == true){
            close_serialport();
            link_close_Toast_text = "链接已关闭";
            link_close_Toast = true;

            $link_working = false;
        }else{
            link_close_Toast_text = "未链接端口";
            link_close_Toast = true;
        }

        setTimeout(() => {link_close_Toast = false}, 3000);
    }

</script>

<div class="grid mx-8 justify-self-start absolute">
    <Toast transition={slide} params={{ delay: 250, duration: 500, easing: quintOut }} color="red" toastStatus={link_error_Toast}>
        <svelte:fragment slot="icon">
        <ExclamationCircleSolid class="w-5 h-5" />
        <span class="sr-only">Warning icon</span>
        </svelte:fragment>
        链接失败:{link_error_Toast_text}
    </Toast>
    <Toast transition={slide} params={{ delay: 250, duration: 500, easing: quintOut }} color="green" toastStatus={link_OK_Toast}>
        <svelte:fragment slot="icon">
        <CheckCircleSolid class="w-5 h-5" />
        <span class="sr-only">success icon</span>
        </svelte:fragment>
        链接成功
    </Toast>
    <Toast transition={slide} params={{ delay: 250, duration: 500, easing: quintOut }} color="green" toastStatus={link_OKed_Toast}>
        <svelte:fragment slot="icon">
        <CheckCircleSolid class="w-5 h-5" />
        <span class="sr-only">success icon</span>
        </svelte:fragment>
        已链接
    </Toast>
    <Toast transition={slide} params={{ delay: 250, duration: 500, easing: quintOut }} color="yellow" toastStatus={link_close_Toast}>
        <svelte:fragment slot="icon">
        <CheckCircleSolid class="w-5 h-5" />
        <span class="sr-only">success icon</span>
        </svelte:fragment>
        关闭链接:{link_close_Toast_text}
    </Toast>
</div>

<div transition:slide class="mt-2 max-w-full grid place-items-center">
    
    <div class="bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400 rounded-lg border border-gray-200 dark:border-gray-700 divide-gray-200 dark:divide-gray-700 shadow-md flex flex-col p-4 sm:p-6 w-1/2 transition-shadow duration-300 ease-in-out hover:shadow-lg ">
        <div class="flew w-full justify-center text-center border-b-2">
            <Label class="m-2 text-2xl opacity-80">串口连接设置</Label>
            <!-- <Button onclick={() => {update_Serial_select()}}></Button> -->
        </div>
        {#each SerialArray as i }
            <div class="flex justify-between">
                <Serial name={i}></Serial>
            </div>
        {/each}
        <div class="flex justify-between">
            <div class="m-2">
                <Label class="m-2 text-lg ">训练模式发送速度</Label>
            </div>
            <div class="m-3">
                <ButtonGroup>
                    <NumberInput type="text" id="send_rate" bind:value={$send_rate} />
                    <InputAddon>ms</InputAddon>
                </ButtonGroup>
            </div>
        </div>
        <div class="grid grid-cols-2 gap-4 justify-self-end">
            <Button class="col-start-1" onclick={() => {link()}}>链接</Button>
            {#if $link_working }
            <div transition:slide>
                <Button class="col-start-2 w-[100%]" color="red" onclick={() => {close_link()}}>关闭链接</Button>
            </div>
            {/if}
        </div>
        {#if $link_working }
        <div transition:slide class="grid grid-cols-3 gap-4 justify-self-end py-4">
            <Button disabled={$cancelmotioning} color="yellow" class="col-start-2" onclick={() => {
                if ($cancelmotioning){
                    console.log("shabi")
                }else{
                    send_serial_emit("z");
                }
                }}>单片机初始化</Button>
        </div>
        {/if}
        <div>
            <pre>{$temp_str}</pre>
        </div>
    </div>
</div>

